package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsCartMapper;
import com.qf.mapper.DtsCategoryMapper;
import com.qf.pojo.DtsCategory;
import com.qf.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.lang.model.element.VariableElement;
import java.util.Date;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private DtsCategoryMapper categoryMapper;

    @Override
    public List<DtsCategory> selectById(DtsCategory category) {
        QueryWrapper<DtsCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid", category.getId());
        queryWrapper.eq("deleted", 0);

        List<DtsCategory> categories = categoryMapper.selectList(queryWrapper);
        return categories;
    }

    @Override
    public List<DtsCategory> selectByPid() {
        QueryWrapper<DtsCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid", 0);
        queryWrapper.eq("deleted", 0);

        List<DtsCategory> categories = categoryMapper.selectList(queryWrapper);
        return categories;
    }

    @Override
    public int add(DtsCategory category) {
        category.setAddTime(new Date());
        category.setUpdateTime(new Date());
        category.setDeleted(false);

        int count = categoryMapper.insert(category);
        return count;
    }

    @Override
    public int update(DtsCategory category) {
        category.setUpdateTime(new Date());

        int count = categoryMapper.updateById(category);
        return count;
    }

    @Override
    public void deleteById(DtsCategory category) {
        Integer id = category.getId();
        categoryMapper.deleteById(id);
    }

    @Override
    public IPage<DtsCategory> findByPage(Integer page, Integer limit, Integer id, String name, String sort, String order) {
        Page<DtsCategory> pageParam = new Page<>(page, limit);
        QueryWrapper<DtsCategory> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(id)){
            queryWrapper.like("id", id);
        }
        if (!StringUtils.isEmpty(name)){
            queryWrapper.like("name", name);
        }
        if ("asc".equalsIgnoreCase(order)){
            queryWrapper.orderByAsc(sort);
        }else {
            queryWrapper.orderByDesc(sort);
        }

        Page<DtsCategory> selectPage = categoryMapper.selectPage(pageParam, queryWrapper);
        return selectPage;
    }

}
